<?php
namespace app\mini\controller\commons;

use app\common\exception\UploadException;
use app\common\library\exception\ApiException;
use app\common\library\Upload;
use app\common\traits\InterfacesExceptionTrait;
use think\Config;

class File extends Base
{
    use InterfacesExceptionTrait;

    /**
     * 文件上传公共方法
     * @return \think\response\Json
     * @throws ApiException
     */
    public function uploads()
    {
        $attachment = null;
        //默认普通上传文件
        $file = $this->request->file('file');
        $type = $this->request->param('file_type','');
        $saveKey = 'uploads/';
        switch ($type)
        {
            case 0:

                break;
            case 1: //添加保养记录上传的图片
                $saveKey = "uploads/maintain/";
                break;
            case 2://车辆更多信息上传的图片
                $saveKey = "uploads/car/";
                break;
            case 3://商机图片
                $saveKey = "uploads/service/";
                break;
            case 4://评论图片
                $saveKey = "uploads/comment/";
                break;
            case 5://用户头像
                $saveKey = "uploads/head/";
                break;
            default:

        }
        //必须设定cdnurl为空,否则cdnurl函数计算错误
        Config::set('upload.cdnurl', '');
        try {
            $upload = new Upload($file);
            $attachment = $upload->upload($saveKey.md5(time().rand(1000,9999)));
        } catch (UploadException $e) {
            throw new ApiException($e->getMessage(), 200);
        }
        return $this->response(['url' =>cdnurl($attachment->url, true)]);
    }

}